package cn.com.startai.smartadh5.main.service.musicplayer;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.com.startai.smartadh5.db.db.entity.PlayInfo;
import cn.com.startai.smartadh5.db.sp.SPManager;
import cn.com.startai.smartadh5.main.receiver.musicplayer.NoisyAudioStreamReceiver;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayLoopModeBean;


/**
 * 音乐播放后台服务
 * Created by wcy on 2015/11/27.
 */
public class PlayService extends Service implements MediaPlayer.OnCompletionListener {
    private static final String TAG = "Service";
    private static final long TIME_UPDATE = 300L;

    private static final int STATE_IDLE = 0;
    private static final int STATE_PREPARING = 1;
    private static final int STATE_PLAYING = 2;
    private static final int STATE_PAUSE = 3;

    private final NoisyAudioStreamReceiver mNoisyReceiver = new NoisyAudioStreamReceiver();
    private final IntentFilter mNoisyFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    private final Handler mHandler = new Handler();
    private MediaPlayer mPlayer = new MediaPlayer();
//    private AudioFocusManager mAudioFocusManager;
//    private MediaSessionManager mMediaSessionManager;
    private OnPlayerEventListener mListener;
    // 正在播放的歌曲[本地|网络]
    private PlayInfo mPlayingMusic;
    // 正在播放的本地歌曲的序号
    private int mPlayingPosition = -1;
    private int mPlayState = STATE_IDLE;
    //播放列表
    private List<PlayInfo> playList = new ArrayList<>();

    private int loopMode;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: " + getClass().getSimpleName());
//        mAudioFocusManager = new AudioFocusManager(this);
//        mMediaSessionManager = new MediaSessionManager(this);
        mPlayer.setOnCompletionListener(this);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    public static void startCommand(Context context, String action) {
        Intent intent = new Intent(context, PlayService.class);
        intent.setAction(action);
        context.startService(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case Actions.ACTION_MEDIA_PLAY_PAUSE:
                    playPause();
                    break;
                case Actions.ACTION_MEDIA_NEXT:
                    next();
                    break;
                case Actions.ACTION_MEDIA_PREVIOUS:
                    prev();
                    break;
                default:
                    break;
            }
        }
        return START_NOT_STICKY;
    }

    public void setPlayList(List<PlayInfo> playList){
        this.playList.clear();
        this.playList.addAll(playList);
    }

    public void addPlayList(List<PlayInfo> playList) {
        this.playList.addAll(playList);
    }
    @Override
    public void onCompletion(MediaPlayer mp) {
//        next();
        switch (SPManager.getInstance().getCurrentLoopMode()) {
            case PlayLoopModeBean.MODE_RANDOM:
                mPlayingPosition = new Random().nextInt(playList.size());
                play(mPlayingPosition);
                break;
            case PlayLoopModeBean.MODE_SINGLE_CYCLE:
                play(mPlayingPosition);
                break;
            case PlayLoopModeBean.MODE_LOOP:
            default:
                play(mPlayingPosition + 1);
                break;
        }
    }

    public OnPlayerEventListener getOnPlayEventListener() {
        return mListener;
    }

    public void setOnPlayEventListener(OnPlayerEventListener listener) {
        mListener = listener;
    }

    public void play(int position) {
        if (playList.isEmpty()) {
            return;
        }

        if (position < 0) {
            position = playList.size() - 1;
        } else if (position >= playList.size()) {
            position = 0;
        }

        mPlayingPosition = position;
        PlayInfo music = playList.get(mPlayingPosition);
        SPManager.getInstance().saveCurrentAudioPlayId(music.getId());
        play(music);
    }

    private void play(PlayInfo music) {
        mPlayingMusic = music;
        try {
            mPlayer.reset();
            mPlayer.setDataSource(music.getFilePath());
            mPlayer.prepareAsync();
            mPlayState = STATE_PREPARING;
            mPlayer.setOnPreparedListener(mPreparedListener);
            mPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
            if (mListener != null) {
                mListener.onChange(music);
            }
//            mMediaSessionManager.updateMetaData(mPlayingMusic);
//            mMediaSessionManager.updatePlaybackState();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            if (isPreparing()) {
                start();
            }
        }
    };

    private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            if (mListener != null) {
                mListener.onBufferingUpdate(percent);
            }
        }
    };

    public void playPause() {
        if (isPreparing()) {
            stop();
        } else if (isPlaying()) {
            pause();
        } else if (isPausing()) {
            start();
        } else {
            play(getPlayingPosition());
        }
    }

    public void start() {
        if (!isPreparing() && !isPausing()) {
            return;
        }

//        if (mAudioFocusManager.requestAudioFocus()) {
            mPlayer.start();
            mPlayState = STATE_PLAYING;
            mHandler.post(mPublishRunnable);
//            mMediaSessionManager.updatePlaybackState();
            registerReceiver(mNoisyReceiver, mNoisyFilter);

            if (mListener != null) {
                    mListener.onPlayerStart();
            }
//        }
    }

    public void pause() {
        if (!isPlaying()) {
            return;
        }

        mPlayer.pause();
        mPlayState = STATE_PAUSE;
        mHandler.removeCallbacks(mPublishRunnable);
//        mMediaSessionManager.updatePlaybackState();
        unregisterReceiver(mNoisyReceiver);

        if (mListener != null) {
            mListener.onPlayerPause();
        }
    }

    public void stop() {
        if (isIdle()) {
            return;
        }
        pause();
        mPlayer.reset();
        mPlayState = STATE_IDLE;
    }

    public void next() {
        if (playList.isEmpty()) {
            return;
        }
        if(loopMode==PlayLoopModeBean.MODE_RANDOM){
            mPlayingPosition = new Random().nextInt(playList.size());
            play(mPlayingPosition);
        }else {
            play(mPlayingPosition + 1);
        }
        Log.i("PlayService","loopMode="+loopMode);
    }

    public void prev() {
        if (playList.isEmpty()) {
            return;
        }


         if(loopMode==PlayLoopModeBean.MODE_RANDOM){
            mPlayingPosition = new Random().nextInt(playList.size());
            play(mPlayingPosition);
        }else {
             play(mPlayingPosition - 1);
         }
        Log.i("PlayService","loopMode="+loopMode);
    }

    /**
     * 设置循环模式
     * @param loopMode
     */
    public void setLoopMode(int loopMode) {
        this.loopMode = loopMode;
    }

    /**
     * 删除播放记录
     * @param removedPosition 需要删除音乐的 position
     * @return 删除后的列表集合
     */
    public List<PlayInfo> removePlayInfo(int removedPosition){
        if(mPlayingPosition == removedPosition && playList.size() == 1) {
            clearPlayList();
        } else if(mPlayingPosition == removedPosition){
            playList.remove(removedPosition);
            play(mPlayingPosition);
        } else if(removedPosition <= playList.size() - 1){
            playList.remove(removedPosition);
        }
        return playList;
    }

    /**
     * 清空播放列表
     */
    public void clearPlayList(){
        playList.clear();
        mPlayingPosition = -1;
        mPlayingMusic = null;
        stop();
    }

    /**
     * 跳转到指定的时间位置
     *
     * @param msec 时间
     */
    public void seekTo(int msec) {
        if (isPlaying() || isPausing()) {
            mPlayer.seekTo(msec);
//            mMediaSessionManager.updatePlaybackState();
            if (mListener != null) {
                mListener.onPublish(msec);
            }
        }
    }

    public boolean isPlaying() {
        return mPlayState == STATE_PLAYING;
    }

    public boolean isPausing() {
        return mPlayState == STATE_PAUSE;
    }

    public boolean isPreparing() {
        return mPlayState == STATE_PREPARING;
    }

    public boolean isIdle() {
        return mPlayState == STATE_IDLE;
    }

    /**
     * 获取正在播放的本地歌曲的序号
     */
    public int getPlayingPosition() {
        return mPlayingPosition;
    }

    /**
     * 获取正在播放的歌曲[本地|网络]
     */
    public PlayInfo getPlayingMusic() {
        return mPlayingMusic;
    }

    /**
     * 删除或下载歌曲后刷新正在播放的本地歌曲的序号
     */
//    public void updatePlayingPosition() {
//        int position = 0;
//        long id = Preferences.getCurrentSongId();
//        for (int i = 0; i < AppCache.get().getMusicList().size(); i++) {
//            if (AppCache.get().getMusicList().get(i).getId() == id) {
//                position = i;
//                break;
//            }
//        }
//        mPlayingPosition = position;
//        Preferences.saveCurrentSongId();
//    }

    public int getAudioSessionId() {
        return mPlayer.getAudioSessionId();
    }

    public long getCurrentPosition() {
        if (isPlaying() || isPausing()) {
            return mPlayer.getCurrentPosition();
        } else {
            return 0;
        }
    }

    private Runnable mPublishRunnable = new Runnable() {
        @Override
        public void run() {
            if (isPlaying() && mListener != null) {
                mListener.onPublish(mPlayer.getCurrentPosition());
            }
            mHandler.postDelayed(this, TIME_UPDATE);
        }
    };

    @Override
    public void onDestroy() {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
//        mAudioFocusManager.abandonAudioFocus();
//        mMediaSessionManager.release();
        super.onDestroy();
        Log.i(TAG, "onDestroy: " + getClass().getSimpleName());
    }

    public void quit() {
        stop();
        stopSelf();
    }

    public class PlayBinder extends Binder {
        public PlayService getService() {
            return PlayService.this;
        }
    }
}
